/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.martinimix.validation;

import java.util.Arrays;
import java.util.Collection;

import org.springframework.validation.Errors;

/**
 * Provides a single selection field validator.
 * 
 * @author Scott Rossillo
 *
 */
public class SimpleSingleSelectionValidator implements SingleSelectionValidator {

	private Collection validValues;

	/**
	 * Creates a new single selection field validator.
	 */
	public SimpleSingleSelectionValidator() { }
	
	/**
	 * Creates a new single selection field validator with the given
	 * valid values.
	 * 
	 * @param validValues an array of valid field values
	 */
	public SimpleSingleSelectionValidator(String[] validValues) {
		this.setValidValues(validValues);
	}

	/**
	 * Return true if the selected value is a represents a valid value
	 * for the field being validated.
	 * 
	 * @param selectedValue the field value to validate
	 * 
	 * @return <code>true</code> if <code>selectedValue</code> is
	 * valid field value; <code>false</code> otherwise
	 */
	protected final boolean isValueSelected(Object selectedValue) {

		return validValues.contains(selectedValue);
	}

	/* (non-Javadoc)
	 * @see net.martinimix.validation.SingleSelectionValidator#rejectIfNotSelected(org.springframework.validation.Errors, java.lang.String, java.lang.String)
	 */
	public void rejectIfNotSelected(Errors errors, String field, String code) {

		if(!this.isValueSelected(errors.getFieldValue(field))) {
			errors.rejectValue(field, code);
		}
	}

	/* (non-Javadoc)
	 * @see net.martinimix.validation.SingleSelectionValidator#rejectIfNotSelected(org.springframework.validation.Errors, java.lang.String, java.lang.String, java.lang.String)
	 */
	public void rejectIfNotSelected(Errors errors, String field, String code, String defaultMessage) {
		
		if(!this.isValueSelected(errors.getFieldValue(field))) {
			errors.rejectValue(field, code, defaultMessage);
		}
	}
	
	public void setValidValues(String[] validValues) {
		
		this.validValues = Arrays.asList(validValues);
	}

}
